<template>
    <div class="wrap">
        <div class="mt-2 align-items-center informationHeader">
            <label class="set-title">{{ $t('message.materialLibraryManager.setQuery') }}</label>
            <div class="queryInput">
                <el-input v-model="keyWords" @keyup.native.enter="queryMaterialLibraryItem" clearable
                          placeholder="请输入搜索内容" @input="handleEmpty">
                    <el-button slot="append" icon="el-icon-search" @click="queryMaterialLibraryItem"></el-button>
                </el-input>
            </div>
        </div>
        <div class="tableContainer">
            <div class="option">
                <label class="set-title">{{ $t('message.materialLibraryManager.option') }}</label>
                <div class="mt-2 mb-2">
                    <el-button type="primary"
                               @click="addItem">{{ $t('message.materialLibraryManager.add') }}
                    </el-button>
                    <el-button type="primary"
                               @click="deleteMaterialLibraryItem">{{ $t('message.materialLibraryManager.delete') }}
                    </el-button>
                    <el-button type="primary"
                               @click="updateItem">{{ $t('message.materialLibraryManager.update') }}
                    </el-button>
                </div>
            </div>
            <div class="d-flex align-items-center" v-if="this.materialLibraryData">
                <el-table
                        ref="table"
                        width="100%"
                        height="tableHeight + 'px'"
                        :data="materialLibraryData" highlight-current-row
                        :row-style="{height: '0'}"
                        :cell-style="{padding: '1px'}" border style="width: 100%;font-size: 13px;"
                        v-bind:style="{ height: materialLibraryData.length?'320px' : '100px' }"
                        @row-click="handleRowClick">
                    <el-table-column
                            prop="number"
                            :label="$t('message.materialLibraryManager.number')"
                            align="center"
                            width="100"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="name"
                            :label="$t('message.materialLibraryManager.name')"
                            align="center"
                            width="150"
                    >
                    </el-table-column>
                    <el-table-column
                            prop=level
                            sortable
                            :label="$t('message.materialLibraryManager.level')"
                            align="center"
                            width="180"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="area"
                            sortable
                            :label="$t('message.materialLibraryManager.area')"
                            align="center"
                            width="180"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="density"
                            sortable
                            :label="$t('message.materialLibraryManager.density')"
                            align="center"
                            width="157"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="standard"
                            sortable
                            :label="$t('message.materialLibraryManager.standard')"
                            align="center"
                            width="180"
                    >
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <material-library-dialog :dialogVisible="dialogVisible" :selected-row-data="setSelectedRowData"
                                 :selected-row-number="setSelectedRowNumber"
                                 :option-type="optionType" @close-manager-dialog="closeDialog"
                                 @confirm-manager-dialog="dialogConfirm"></material-library-dialog>
        <div class="btn">
            <el-button size="small"
                       @click="cancel">{{ $t('message.common.cancel') }}
            </el-button>
        </div>
    </div>
</template>

<script>
import dialogMixin from "../DialogMixin";
import {materialLibraryCommand} from "../../../command/MaterialLibraryCommand";
import MaterialLibraryDialog from "./MaterialLibraryDialog.vue";

export default {
    name: "MaterialLibrary",
    components: {MaterialLibraryDialog},
    mixins: [dialogMixin],
    data() {
        return {
            isInit: false,
            fileLimitNum: 1,
            errorMessage: '',
            fileSize: 0,
            totalSize: 0,
            files: null,
            isExcel: false,
            isExcelFileType: ['xls', 'xlsx'],
            materialLibraryData: [],
            selectedRowData: {},//某点选行数据
            setSelectedRowData: {},
            setSelectedRowNumber: '',
            dialogVisible: false,
            optionType: 0,
            keyWords: "",
        }
    },
    mounted() {
        if (!this.isInit) {
            materialLibraryCommand.init(1200, 1200, 1200, () => {
                materialLibraryCommand.clearAllHighLight();
                this.getData();
                this.isInit = true;
            })
        }
    },
    methods: {
        changePluginContainerHeight() {
            materialLibraryCommand.changePluginContainerHeight({
                minWidth: this.$el.clientWidth,
                maxHeight: this.$el.clientHeight + 10,
                width: 980
            })
        },
        cancel() {
            materialLibraryCommand.closeActiveCmd();
        },
        //上传和导入excel文件
        importFile() {
            materialLibraryCommand.parseExcel(this.files, res => {
                console.log(res);
            });
        },
        //获取材料库数据
        getData() {
            materialLibraryCommand.getMaterialLibraryDate(res => {
                this.materialLibraryData = res;
            });
        },
        //设置鼠标点击事件，回填数据到表单中
        handleRowClick(row, column, event) {
            this.selectedRowData = {};
            this.selectedRowData = {...row};//获取某个点选行数据
            //获取点选行的字段名,将名字设置给input表单
        },
        isEmpty(obj) {
            return Object.keys(obj).length === 0 && obj.constructor === Object;
        },
        closeDialog(val) {
            this.dialogVisible = val;
        },
        dialogConfirm(val) {
            if (!this.optionType) {
                this.addMaterialLibraryItem(val);
                this.dialogVisible = false;
            } else {
                this.updateMaterialLibraryItem(val);
                this.dialogVisible = false;
            }
        },
        addItem() {
            this.optionType = 0;
            this.dialogVisible = true;
            this.setSelectedRowData = {};
        },
        updateItem() {
            if (!this.isEmpty(this.selectedRowData)) {
                this.optionType = 1;
                this.dialogVisible = true;
                this.setSelectedRowData = this.selectedRowData;
                this.setSelectedRowNumber = this.selectedRowData.number;
            } else {
                materialLibraryCommand.eventBusAlertMsg('请先选择表格中某行数据再进行修改', 'warning');
            }
        },
        //添加某个材质库项
        addMaterialLibraryItem(val) {
            let info = val;
            materialLibraryCommand.getMaterialLibraryDate(res => {
                let numberList = res.map(item => item.number);
                if (numberList.includes(info.number)) {
                    materialLibraryCommand.eventBusAlertMsg('材料编号不能重复', 'error');
                } else {
                    materialLibraryCommand.addMaterialLibraryItem(info, res => {
                        this.materialLibraryData = [];
                        this.materialLibraryData = res;
                    })
                }
            });
        },
        //删除某材质库项
        deleteMaterialLibraryItem() {
            let info = this.selectedRowData;
            let id = info.id ?? "";
            if (id && id !== "") {
                materialLibraryCommand.deleteMaterialLibraryItem(id, res => {
                    this.materialLibraryData = [];
                    this.materialLibraryData = res;
                })
            } else {
                this.eventBusAlertMsg('请先选择表格中某行数据', 'warning');
            }
        },
        //修改某材质项
        updateMaterialLibraryItem() {
            let info = this.selectedRowData;
            let id = info.id ?? "";
            if (id && id !== "") {
                materialLibraryCommand.updateMaterialLibraryItem(info, res => {
                    this.materialLibraryData = [];
                    this.materialLibraryData = res;
                })
                //如果id存在且不为空,，修改
            } else {
                //id为空，新增
                materialLibraryCommand.addMaterialLibraryItem(info, res => {
                    this.materialLibraryData = [];
                    this.materialLibraryData = res;
                })
            }

        },
        handleEmpty() {
            let keyWords = this.keyWords;
            if (keyWords === "") {
                this.getData();
            }
        },
        //查询某材质库项
        queryMaterialLibraryItem() {
            let keyWords = this.keyWords;
            if (keyWords === "") {
                this.getData();
            } else {
                materialLibraryCommand.queryMaterialLibraryList(keyWords, res => {
                    this.materialLibraryData = [];
                    this.materialLibraryData = res;
                })
            }
        },
        getAcceptTypes() {
            let typeList = ["xls", "xlsx"];
            return typeList;
        },
        getFile(file, fileList) {
            //用户选择文件或者拖放文件到上传区域时触发
            this.files = [];
            this.checkOnlyExcel(fileList);
            this.checkFileList(file, fileList)
        },
        removeFile(file, fileList) {
            //用户删除已选中的而文件时触发
            this.files = [];
            this.checkOnlyExcel(fileList);
            this.checkFileList(file, fileList)
        },
        //超出限制数量的回调
        handleExceed() {
            materialLibraryCommand.eventBusAlertMsg("一次只能上传一个文件", "warning");
        },
        //获取文件类型
        getFileType(fileName) {
            let delimiterIndex = fileName.lastIndexOf('.');
            return fileName.substring(delimiterIndex + 1).toLowerCase();
        },
        //检测是否只有excel类型的文件
        checkOnlyExcel(fileList) {
            this.onlyXMLFile = fileList?.length ? fileList?.some(file => {
                let extStartIndex = file.name.lastIndexOf(".");
                let ext = file.name.substring(extStartIndex + 1, file.name.len);
                return ext.toLowerCase() === "xls" || ext.toLowerCase() === "xlsx"
            }) : false;
        },
        checkFileList(file, list) {
            this.errorMessage = '';
            this.fileSize = 0;
            this.totalSize = 0;
            this.isExcel = !!list.some(fileItem => this.isExcelFileType.includes(this.getFileType(fileItem.name).toLowerCase()));
            if (list.length === 0) {
                this.errorMessage = '';
            } else {
                let _list = [];
                list.forEach(fileItem => {
                    // this.files = fileItem.raw;
                    this.files = fileItem;
                    this.totalSize += fileItem.size;
                    this.fileSize += 1;
                    if (!_list.includes(fileItem.name)) {
                        _list.push(fileItem.name)
                    }
                    if (!this.checkFormat(fileItem.name, this.getAcceptTypes) || fileItem.raw.isDirectory) {
                        this.errorMessage = this.$t('message.FastenerInstantiatedTool.importType');//文件类型错误
                    }
                });
                if (list.length !== _list.length) {
                    this.errorMessage = this.$t('message.FastenerInstantiatedTool.existsSameName');//文件已选择
                }
                if (this.fileSize > 1) {
                    this.errorMessage = this.$t('message.FastenerInstantiatedTool.outLimitCount');//超出文件限制数量
                } else if (this.totalSize > this.getAcceptSize) {
                    this.errorMessage = this.$t('message.FastenerInstantiatedTool.outLimitSize');//超出文件限制大小
                }
            }
        },
        checkFormat(fileName, acceptTypes) {
            let delimiterIndex = fileName.indexOf('.');
            let fileType = fileName.substring(delimiterIndex + 1).toLowerCase();
            let find = false;
            for (let i = 0; i < acceptTypes.length; ++i) {
                if (fileType.includes(acceptTypes[i])) {
                    find = true;
                    break;
                }
            }
            return find;
        },
    },
    computed: {},
}
</script>

<style scoped>

.wrap {
    font-size: 12px;
    overflow: hidden;
}

.set-title {
    font-size: 14px;
    color: #333333;
}

.informationHeader {
    margin: 0.5rem;
    padding: 1rem 0;
    border-bottom: 2px solid var(--bg-color3);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.queryInput {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 200px;
}

.queryInput >>> .el-input__inner {
    border: 2px solid var(--bg-color3);
    line-height: 26px;
    border-radius: 4px 0 0 4px;
}

.tableContainer {
    padding: 0 0.5rem;
}

.option {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}

.form-table {
    display: flex;
    flex-wrap: wrap;
}

.form-table .el-form-item {
    flex: 1 1 calc(16.67% - 76px);
    padding: 5px;
}

.el-form--inline {
    width: 100%;
}

.el-form--inline .el-form-item {
    margin: 0px;
}

>>> .el-form-item__label {
    margin-right: 5px !important;
    padding-right: 10px;
    display: flex;
}

>>> .el-input__suffix {
    padding-top: 5px;
}


</style>